/* eslint-disable react/no-danger */
import { useEffect } from 'react';

import { articleApi } from '@/entities/article';
import { getIsAuth, getUserId } from '@/entities/auth/model/selectors';
import { CourseCard, productApi } from '@/entities/course';
import { AddToFavourite } from '@/features/AddToFavourite';
import { BackButton } from '@/features/BackButton';
import { OpenShareModalButton } from '@/features/Share';
import { innerUrls } from '@/shared/constants';
import { getImageUrl } from '@/shared/lib';
import { usePrevRouter } from '@/shared/lib/hooks';
import { useAppSelector } from '@/shared/store';
import { Accordion, Container, Grid, SpeakerCard, Title, Wrapper } from '@/shared/ui';
import { Footer } from '@/widgets/Footer';
import { Header } from '@/widgets/Header';
import { References } from '@/widgets/References';
import dayjs from 'dayjs';
import Image from 'next/image';
import { useIsClient } from 'usehooks-ts';

import cs from './Article.module.scss';
import { ArticlePageLoader } from './ArticlePageLoader';

export const Article = ({ id }: { id: string }) => {
  const isAuth = useAppSelector(getIsAuth);
  const userId = useAppSelector(getUserId);
  const { data: article, isLoading } = articleApi.useGetSingleArticleQuery(id);
  const [addToFavourites, { isLoading: isAdding }] = articleApi.useAddArticleToFavouritesMutation();
  const [deleteFromFavourites, { isLoading: isDeleting }] = articleApi.useDeleteArticleFromFavouritesMutation();
  const [setViewed] = articleApi.useSetArticleViewedMutation();

  const { data: sources } = articleApi.useGetArticleSourcesQuery(id);

  const isClient = useIsClient();
  const { data: courses } = productApi.useGetProductsQuery(
    {
      limit: 8,
      'filters[topics]': article?.topics?.map((v) => v.id).toString(),
    },
    { skip: !article?.topics?.length },
  ); // 'filters[formats]': article?.format.id?.toString(),

  useEffect(() => {
    setViewed(id);
  }, []);
  const prevRouter = usePrevRouter();
  return (
    <>
      <Header />
      <Wrapper>
        <Container>
          <BackButton
            className={cs.back}
            defaultBackLink={
              prevRouter?.pathname?.startsWith(innerUrls.articles) ? prevRouter?.asPath : innerUrls.articles
            }
            text="Статьи"
          />
          {isLoading && <ArticlePageLoader />}
          {!isLoading && (
            <div className={cs.container}>
              <div className={cs.article}>
                <div className={cs.description}>
                  <div className={cs.title}>
                    <Title tag="h1">{article?.title}</Title>
                    {isClient && (
                      <div className={cs.actions}>
                        <OpenShareModalButton
                          data={{ title: article?.title, url: window.location.href }}
                          variant="icon"
                        />
                        <AddToFavourite
                          errorMessage={{
                            onAdd: 'Ошибка при добавлении в избранное: ',
                            onDelete: 'Ошибка при удалении из избранного: ',
                          }}
                          handleAdd={() => addToFavourites({ id: userId?.toString(), articleId: id }).unwrap()}
                          handleDelete={() => deleteFromFavourites({ id: userId?.toString(), articleId: id }).unwrap()}
                          isFavourite={!!article?.isFavorite}
                          isHidden={!isAuth}
                          isLoading={isAdding || isDeleting}
                          successMessage={{ onAdd: 'Добавлено в избранное', onDelete: 'Удалено из избранного' }}
                        />
                      </div>
                    )}
                  </div>
                  <p className={cs.date}>{dayjs(article?.publishedAt).format('DD MMMM YYYY')}</p>
                </div>
                {!!article?.author && (
                  <div className={cs.author}>
                    <SpeakerCard
                      description={article?.author?.positionAtWork}
                      image={article?.author?.avatar}
                      name={article?.author?.name}
                    />
                    <div className={cs.hr} />
                  </div>
                )}
                {!!article?.image && (
                  <div className={cs.main_image}>
                    <Image alt={article?.title} fill src={getImageUrl(article?.image)} />
                  </div>
                )}
                {!!article?.body && (
                  <div className={cs.article_body}>
                    <div dangerouslySetInnerHTML={{ __html: article?.body }}></div>
                  </div>
                )}
                <div className={cs.hr} />

                {!!sources?.sources?.length && (
                  <div className={cs.sources_container}>
                    <Accordion
                      item={{
                        id: 0,
                        title: 'Источники',
                        body: (
                          <References
                            sources={sources?.sources?.map(({ title, link }, index) => ({
                              id: index + 1,
                              title,
                              href: link,
                            }))}
                          />
                        ),
                      }}
                      titleClassName={cs.sources_title}
                    />
                  </div>
                )}
              </div>
              {!!courses?.courses?.length && (
                <div className={cs.suggestions}>
                  <h3 className={cs.small_title}>Советуем</h3>
                  <Grid size="l">
                    {courses.courses.map(({ id, product }) => (
                      <div className={cs.card} key={id}>
                        <CourseCard
                          discount={product.discount}
                          discountPrice={product.discountPrice}
                          id={id}
                          image={product.image}
                          isTip
                          price={product.price}
                          rate={product.averageRate as unknown as number}
                          target="_blank"
                          title={product.title}
                        />
                      </div>
                    ))}
                  </Grid>
                </div>
              )}
            </div>
          )}
        </Container>
      </Wrapper>
      <Footer />
    </>
  );
};
